package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Cliente;
import dao.ClienteDAO;

@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String email = request.getParameter("email");
		String senha = request.getParameter("senha");
		
		ClienteDAO clDAO = new ClienteDAO();

		Cliente cliente_logado = clDAO.recuperarCliente(email, senha);
		
		if (cliente_logado == null) {
			
			request.setAttribute("loginErro", "Dados incorretos!");
			
			RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
			
			rd.forward(request,response);
			
		} else {
			
			HttpSession sessao = request.getSession(true);
			
			sessao.setAttribute("cliente_logado", cliente_logado);
			sessao.setAttribute("nomeClienteLogado", cliente_logado.getNome());
			
			RequestDispatcher rd = request.getRequestDispatcher("/login-sucesso.jsp");
			
			rd.forward(request,response);
			
		}
		
	}

}
